﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ComputerGraphics.Render;
using ComputerGraphics.Graphics;
using ComputerGraphics.Graphics;
using ComputerGraphics.Geometry;
using System.Drawing;
using ComputerGraphics.Application;
using System.Text.RegularExpressions;

namespace ComputerGraphics
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        ///

        static void Main(String[] args)
        {
            int width = 800, height = 800;
            String inputFn = "", outputFn = "";

            foreach (String s in args)
            {
                if (Regex.IsMatch(s, @"/s:\d+"))
                {
                    Match m = Regex.Match(s, @"/s:(\d+)");
                    width = height = Int32.Parse(m.Groups[1].Value);
                }

                if (Regex.IsMatch(s, @"/i:.+"))
                {
                    Match m = Regex.Match(s, @"/i:(.+)");
                    inputFn = m.Groups[1].Value;
                }

                if (Regex.IsMatch(s, @"/o:.+"))
                {
                    Match m = Regex.Match(s, @"/o:(.+)");
                    outputFn = m.Groups[1].Value;
                }
            }

            if (inputFn.Length == 0 || outputFn.Length == 0)
            {
                Console.WriteLine(@"ComputerGraphics.exe /i:<Input XML Filename> /o:<Output BMP Filename> [/s:<Size Of Output Image>]");
                return;
            }

            Camera cmr = SetXMLReader.ReadCameraFromXML(inputFn);
            Scene scn = SetXMLReader.ReadSceneFromXML(inputFn);
            RecursiveRayTracer rrt = new RecursiveRayTracer(new IntPair(width, height));

            ColorTriple[][] ct = rrt.Render(scn, cmr);
            Bitmap image = new Bitmap(width, height);

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    Color col = Color.FromArgb((int)(Math.Min(ct[i][j].Red, 1) * 255), (int)(Math.Min(ct[i][j].Green, 1) * 255), (int)(Math.Min(ct[i][j].Blue, 1) * 255));
                    image.SetPixel(i, j, col);
                }
            }

            image.Save(outputFn);
        }
    }
}
